'use strict';

const {logger} = require('ee-core/log');
const {exampleService} = require('../service/example');
const {getMainWindow} = require("ee-core/electron");
const {screen, BrowserWindow} = require('electron');
const {json} = require("node:stream/consumers");
let isMouseInWindow = true;
const {sqlitedbService} = require('../service/database/sqlitedb');

/**
 * example
 * @class
 */
class WindowsController {

    /**
     * 所有方法接收两个参数
     * @param args 前端传的参数
     * @param event - ipc通信时才有值。详情见：控制器文档
     *
     */

    addNode(arg, event) {
        logger.info('add------------' + JSON.stringify(arg));
        let win = new BrowserWindow({
            openDevTools: true,
            width: 500,
            height: 400,
            parent: getMainWindow,
            modal: false,
            webPreferences: {
                nodeIntegration: true,
                contextIsolation: false,
            },
        });
        // win.webContents.openDevTools();
        win.loadURL(`http://localhost:8080#/node/add/index`);
        //
        win.webContents.on('did-finish-load', () => {
            logger.info('did-finish-load');
            win.webContents.send('edit-index', arg);
        });


        return 'hello electron-egg';
    }

    async getNotes(arg, event) {
        logger.info('getNotes----------');
        const result = await sqlitedbService.getNotesDataSqlite(0)
        logger.info('getNotes----------', result);
        return result;
    }

     getNotesById(id){
        logger.info('getNotesById----------', id);
        const result =  sqlitedbService.getNotesDataByIdSqlite(id)
        logger.info('getNotesById----------', result);
        return result;
    }

    saveNotes(arg, event) {

        logger.info('saveNodes----------', arg);
        // const info = {title: arg.title, content: arg.content};
        const result =  sqlitedbService.addNotesDataSqlite(arg);
        // const mainWindow = getMainWindow();
        // mainWindow.invoke('refreshNotesList', {})
        // ipc.send('refreshNotesList', {})
        if(result){
            logger.info('send refreshNotesList----------', arg);
            let win = getMainWindow();
            // event.sender.send('refreshNotesList', {});
            win.webContents.send('refreshNotesList', {});
        }

    }


    /**
     * test
     */
    async test() {
        logger.info('Example Controller');
        const result = await exampleService.test('electron');
        logger.info('service result:', result);


        return 'hello electron-egg';
    }

    async drag(arg, event) {
        isMouseInWindow = true;
        const win = getMainWindow();
        win.setPosition(arg.appX, arg.appY);
        // logger.info('service event:', event);
        // const result = await exampleService.test('electron');
        // logger.info('service result:', result);
        this.handleWindowMove(win);

        return 'hello electron-egg';
    }

    async mouseleave(arg, event) {
        logger.info('leave');
        isMouseInWindow = false;
        this.handleWindowMove(getMainWindow())
        return 'hello electron-egg';
    }

    handleWindowMove(mainWindow) {
        if (!mainWindow) return;

        const windowBounds = mainWindow.getBounds();
        const displays = screen.getAllDisplays();

        for (const display of displays) {
            const {x, y, width, height} = display.workArea;

            // 判断窗口是否靠近屏幕边缘
            if (
                // (windowBounds.x <= x + 5 && windowBounds.x >= x - 5) || // 左边缘
                (windowBounds.y <= y + 5 && windowBounds.y >= y - 5) || // 上边缘
                (windowBounds.x + windowBounds.width >= x + width - 5 && windowBounds.x + windowBounds.width <= x + width + 5)  // 右边缘
                // (windowBounds.y + windowBounds.height >= y + height - 5 && windowBounds.y + windowBounds.height <= y + height + 5) // 下边缘
            ) {
                if (!isMouseInWindow) {
                    logger.warn('隐藏');
                    // this.fadeOut(mainWindow);
                }
            } else {
                //this.fadeIn(mainWindow);
            }
        }
    }

    fadeOut(window) {
        let opacity = 1;
        const intervalId = setInterval(() => {
            opacity -= 0.05;
            if (opacity <= 0) {
                clearInterval(intervalId);
                window.hide();
            } else {
                window.setOpacity(opacity);
            }
        }, 50);
    }

    fadeIn(window) {
        window.show();
        let opacity = 0;
        const intervalId = setInterval(() => {
            opacity += 0.05;
            if (opacity >= 1) {
                clearInterval(intervalId);
                window.setOpacity(1);
            } else {
                window.setOpacity(opacity);
            }
        }, 50);
    }

    stickToTop() {
        if (!getMainWindow()) return

        // 确保窗口完全对齐到顶部
        const display = screen.getDisplayNearestPoint({
            x: this.originalBounds.x,
            y: this.originalBounds.y
        })

        this.currentWindow.setBounds({
            x: this.originalBounds.x,
            y: display.bounds.y, // 使用显示器的y坐标确保精确对齐
            width: this.originalBounds.width,
            height: this.originalBounds.height
        })

        this.isSticky = true
        // 初次贴边时自动隐藏
        this.hideWindowWithAnimation()
    }

    hideWindowWithAnimation() {
        if (!this.currentWindow || this.isAnimating) return

        this.isAnimating = true
        this.isHiding = true

        const startBounds = this.currentWindow.getBounds()
        const startTime = Date.now()
        const duration = this.stickyOptions.animationDuration ?? 200
        const startY = startBounds.y
        const targetY = -(startBounds.height - (this.stickyOptions?.visibleSize ?? 5))

        const animate = () => {
            if (!getMainWindow()) {
                this.isAnimating = false
                this.isHiding = false
                return
            }

            const elapsed = Date.now() - startTime
            const progress = Math.min(elapsed / duration, 1)

            // 使用缓动函数使动画更平滑
            const easeProgress = this.easeInOutQuad(progress)
            const newY = startY + (targetY - startY) * easeProgress

            getMainWindow().setBounds({
                ...startBounds,
                y: Math.round(newY)
            })

            if (progress < 1) {
                setImmediate(animate)
            } else {
                this.isAnimating = false
                this.isHiding = false
            }
        }

        setImmediate(animate)
    }

    // 添加缓动函数使动画更平滑
    easeInOutQuad(t) {
        return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t
    }

}

WindowsController.toString = () => '[class WindowsController]';

module.exports = WindowsController;